package com.example.itcacp.service;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    private static final String USER_ITEM_MATRIX_KEY = "user:item:matrix";
    private static final long CACHE_EXPIRE_TIME = 24; // 缓存过期时间（小时）

    private final RedisTemplate<String, Object> redisTemplate;

    public RedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取用户-内容矩阵的 Hash 操作对象
     */
    private HashOperations<String, String, Integer> getMatrixOps() {
        return redisTemplate.opsForHash();
    }

    /**
     * 获取用户的所有内容操作记录
     */
    public Map<String, Integer> getUserItems(Long userId) {
        return getMatrixOps().entries(getKey(userId));
    }

    /**
     * 设置用户对某个内容的操作记录
     */
    public void setUserItem(Long userId, Long contentId, Integer value) {
        getMatrixOps().put(getKey(userId), contentId.toString(), value);
        // 更新缓存过期时间
        redisTemplate.expire(getKey(userId), CACHE_EXPIRE_TIME, TimeUnit.HOURS);
    }

    /**
     * 批量设置用户的内容操作记录
     */
    public void setUserItems(Long userId, Map<String, Integer> items) {
        getMatrixOps().putAll(getKey(userId), items);
        redisTemplate.expire(getKey(userId), CACHE_EXPIRE_TIME, TimeUnit.HOURS);
    }

    /**
     * 检查缓存中是否有用户的内容操作记录
     */
    public boolean hasUserItems(Long userId) {
        return redisTemplate.hasKey(getKey(userId));
    }

    /**
     * 删除用户的内容操作记录
     */
    public void deleteUserItems(Long userId) {
        redisTemplate.delete(getKey(userId));
    }

    /**
     * 构建 Redis key
     */
    private String getKey(Long userId) {
        return USER_ITEM_MATRIX_KEY + ":" + userId;
    }
}
